<?php
// $Id$
/**
 * @file
 *  Responsible for avoiding security risks like JS, MySQL, HTML and PHP injection on forms fields.
 */

/**
 * Preprocess for the website security.
 */
function _website_security_preprocess($form) {
  // Array of validations.
  $array_validations = array(
    '_website_security_check_plain',
  );

  // Prevent running the field validation on admin forms.
  if (
    (arg(0) != 'admin') && // Do not run the validation on admin section.
    !((arg(0) == 'node') && (arg(2) == 'edit')) && // Do not run the validation on node - edit section.
    !((arg(0) == 'node') && (arg(1) == 'add')) // Do not run the validation on node - add section.
    ) {
    $form = _website_security_validation($form, $array_validations);
  }
  return $form;
}


/**
 * Insert the #element_validate attribute for all fields.
 */
function _website_security_validation($form, $array_validations) {
  // Array of field types that will be validate.
  $array_types = array(
    'checkbox',
    'checkboxes',
    'date',
    'password',
    'radio',
    'radios',
    'select',
    'textarea',
    'textfield',
    'hidden',
  );
  foreach ($form as $key => $value) {
    if (is_array($form[$key]) && in_array($form[$key]['#type'], $array_types)) {
      if (!is_array($form[$key]['#element_validate'])) {
        $form[$key]['#element_validate'] = $array_validations;
      }
      else {
        $form[$key]['#element_validate'] = array_merge($form[$key]['#element_validate'], $array_validations);
      }
    }
    if (is_array($form[$key])) {
      $form[$key] = _website_security_validation($form[$key], $array_validations);
    }
  }
  return $form;
}

/**
 * Website security check plain validation.
 */
function _website_security_check_plain($element, &$form_state) {
  if (trim($element['#value']) && !$element['#attributes']['readonly']) {
    if (trim(check_plain(str_replace("'", "", $element['#value'] .''))) != trim(str_replace("'", "", $element['#value']))) {
      form_set_error($element['#name'], t('The field '. $element['#title'] .' contains an illegal character.'));
    }
  }
}
